import { getToken } from '@/utils/cookie'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/b-oj/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/b-oj/layout',
      name: 'layout',
      component: () => import('@/views/Layout.vue'),
      redirect: '/b-oj/layout/cuser',
      children: [
        {
          path: 'cuser',
          name: 'cuser',
          component: () => import('@/views/management/CUser.vue')
        },
        {
          path: 'question',
          name: 'question',
          component: () => import('@/views/management/Question.vue')
        },
        {
          path: 'exam',
          name: 'exam',
          component: () => import('@/views/management/Exam.vue')
        },
        {
          path: 'updateExam',
          name: 'updateExam',
          component: () => import('@/views/management/UpdateExam.vue')
        }
      ]
    }
  ],
})

//路由前置检测
router.beforeEach((to, from,next) => {
  //判断是否存在cookie信息
  if(getToken()) {  //已经登录过了
    if(to.path === '/b-oj/login') {  //已经登录过了，无需登录直接跳转后台管理页面
      next({ path: '/b-oj/layout/cuser' })
    }else {
      next() //该干嘛干嘛去
    }
  }else{ //还未登录
    if(to.path != '/b-oj/login') {   //访问的不是登录页面，强行跳转登录页
      next({ path:'/b-oj/login' })
    }else {
      next()
    }
  }
})

export default router
